﻿
var globalList = {
    imei: [],
    trackDataLastLocation: [],
    trackDataByImei: [],
    users: [],
    customers: [],
    customersGroups: [],
    allCustomers: [],
    allCustomersSelected: [],
    geoFence: [],
    stopsMarkers: []
}

var globalDataSource = {
    usersRoute: [],
    customersGroups: [],
    allCustomers: [],
    allCustomersSelected: [],
    customers: [],
    geoFence: [],
    imei: []
}

var global = {
    refreshIntervalId: null,
    currentGpsPoint: 0,
    currentIndexRoute: -1,
    currentIndexNearClient: -1,
    numPos: 0,
    lastOne: false,
    speedRouteHistory: 1000,
    mtsRoute: null,
    mtsRouteStar: 0.01,
    mtsRouteFix: 0.05,
    mtsStop: 0.025,
    timesStop: 10,
    doesWorkDrawRouteCount: 0,
    origin: null,
    destination: null,
    originClient: null,
    destinationClient: null,
    firstRoute: true,
    firstClientRoute: true,
    doesnWorkDrawRoute: false,
    geoFenceIDSelected: -1,
    lastCardinalPoint: "",
    showNotificationsAlert: true,
    showNotifications: false,
    customerMarker: null,
    currentSlideRouteNumber: 0,
    slideInterval: null,
    username: null,
    usernameSelected: null,
    customerID: null,
    customerGroupID: -1,
    isClear: false,
    route: null,
    timeToCalculateRouteClients: 500
};

var titles = {
    polygonoTitle: "Polígonos",
    customerTitle: "Clientes"
};

var images = {
    location: "../../Template/Vehicles/",
    locationStop: "../../Template/Icon/stop.png",
    locationCustomer: "../../Template/Icon/customer.png"
};

var objXmlControl;
var objMapControl;

jQuery(document).ready(function () {
    if ($(window).height() > 450) {
        document.getElementById('principalPage').attributes.height.value = $(window).height() - 150
    }
    try {
        jQuery.noConflict();
    } catch (e) { };
});

function initialize()
{
    objXmlControl = new XmlControl();
    objMapControl = new MapControl();

    /*var miPopup;
    miPopup = window.open("Account.aspx", "miwin", "width=300,height=150,scrollbars=yes");
    miPopup.focus();*/

    objMapControl.initializeMap();
    global.customerMarker = objMapControl.addCustomerMarker();
    enableDisableSliderRoute(false);
    loadDataGPSTracking();
}

function loadDataGPSTracking()
{
    objMapControl.initializePolygono();
    getGroupsTrackDataLastLocationByUser();
    getAllGeoFenceIntoList();
    getCustomersGroupsByUser();
    getAllForGenerateCustomersRoutes();
    setInterval("getImeiDataTrackLastLocationByUser()", 30000);
    getImeiDataTrackLastLocationByUser();
}

function getAllForGenerateCustomersRoutes()
{
    getUsersByAdmin();
}

function getUsersByAdmin() {

    requestStart(getrpvRoutesPanelUpdateControl());

    PageMethods.wsGetUsersByAdmin(global.username, getUsersByAdminOk, getUsersByAdminError);
}

function getUsersByAdminOk(object)
{
    objXmlControl.openXMLUsersByAdmin(object);
    loadUsersRouteByAdminDataSource();
    responseEnd(getrpvRoutesPanelUpdateControl());
}

function getUsersByAdminError(error)
{
    responseEnd(getrpvRoutesPanelUpdateControl());
    msgError(error.get_message(), titles.customerTitle);
}


function getImeiByUser() {

    requestStart(getrpvRoutesPanelUpdateControl());

    PageMethods.wsGetImeiByUser(global.usernameSelected, getImeiByUserOk, getImeiByUserError);
}

function getImeiByUserOk(object) {
    clearList(globalList.imei);
    objXmlControl.openXMLImeiByUser(object);
    loadImeiDataSource();
    getAllCustomerByUser();
    responseEnd(getrpvRoutesPanelUpdateControl());
}

function getImeiByUserError(error) {
    responseEnd(getrpvRoutesPanelUpdateControl());
    msgError(error.get_message(), titles.customerTitle);
}

function getAllCustomerByUser() {
    requestStart(getrpvRoutesPanelUpdateControl());
    var OrdenColumn = 2; //2.CustomerName, 3.CustomerGroupName
    PageMethods.wsGetAllCustomerByUser(global.usernameSelected, OrdenColumn, getAllCustomerByUserOk, getAllCustomerByUserError);
}

function getAllCustomerByUserOk(object) {
    objXmlControl.openXMLAllCustomerByUser(object);
    loadCustomersGroupsRoutesDataSource();
    responseEnd(getrpvRoutesPanelUpdateControl());
}

function getAllCustomerByUserError(error) {
    responseEnd(getrpvRoutesPanelUpdateControl());
    msgError(error.get_message(), titles.customerTitle);
}

function showNotification(notification, imageLocation, titleNotification) {
    if (global.showNotifications || global.showNotificationsAlert) {

        if (global.showNotificationsAlert)
        {
            global.showNotificationsAlert = false;
            notification = '';
            //imageLocation = null;
            titleNotification = 'Las notificaciones están desabilitadas.';
        }

        var havePermission = window.webkitNotifications.checkPermission();
        if (havePermission == 0) {
            // 0 is PERMISSION_ALLOWED
            var notification = window.webkitNotifications.createNotification(
              imageLocation,
              titleNotification,
            notification
            );

            notification.onclick = function () {
                notification.close();
            }
            notification.show();
        } else {
            window.webkitNotifications.requestPermission();
        }
    }
}

function getImeiValueTreeVehicleSelected() {
    var tree = getMenuVehicleTree();
    var node = tree.get_selectedNode();
    if (node) {
        return node.get_value();
    }
    return -1;
}

function centerImeiTrackDataLastLocationOnClick() {
    var imei = getImeiValueTreeVehicleSelected();
    for (ik = 0; ik < globalList.trackDataLastLocation.length; ik++) {
        if (imei == globalList.trackDataLastLocation[ik].imei) {
            
            setInfoReal(ik);
            objMapControl.clearGeoFenceMarkers(true);
            
            objMapControl.map.setZoom(16);

            loadGeoFenceGridByImei(imei);
            
            try{
                if (globalList.trackDataLastLocation[ik].position == "(NaN, NaN)") {
                    msgInformation('No hay coodenadas de gps definidas para este imei.', 'Posición GPS.');
                }
                else {
                    globalList.trackDataLastLocation[ik].centerMarker();
                }
            }
            catch (e) {
                msgInformation('No hay coodenadas de gps definidas para este imei.', 'Posición GPS.');
            }
            return;
        }
    }

    return -1;
}

function selectLastItemByImei(imei) {
    var masterTable = getGeoFenceGrid();
    masterTable.selectItem(geoFenceListLengthByImei(imei)-1);
}

function selectLastItemByCustomer(id) {
    var masterTable = getCustomerGrid();
    masterTable.selectItem(globalList.customers.length - 1);
}

function geoFenceListLengthByImei(imei)
{
    var length = 0;
    for (i = 0; i < globalList.geoFence.length; i++)
    {
        if (globalList.geoFence[i].imei == imei)
        {
            length++;
        }
    }
    return length;
}

function showHistoryRoute() {
    objMapControl.showHistoryRoute();    
};

function hideHistoryRoute() {
    objMapControl.hideHistoryRoute();
};

function enableDisableGeoFenceEventClickMap() {

    if (getCkbEnableDisableGeoFence().checked) {
        getCkbCustomer().checked = false;
        objMapControl.clearListenerClic();
        objMapControl.setVisibleMarker(global.customerMarker, false);
        objMapControl.setPositionMarker(global.customerMarker, null);
        objMapControl.addListenerClic();
    }
    else {
        objMapControl.clearListenerClic();
        objMapControl.clearGeoFenceMarkers(false);
    }
}

function enableDisableCustomerEventClickMap() {

    if (getCkbCustomer().checked) {
        getCkbEnableDisableGeoFence().checked = false;
        objMapControl.clearListenerClic();
        objMapControl.clearGeoFenceMarkers(false);
        objMapControl.setVisibleMarker(global.customerMarker, true);
        objMapControl.addListenerCustomerClick();
    }
    else {
        objMapControl.clearListenerClic ();
        objMapControl.setVisibleMarker(global.customerMarker, false);
        objMapControl.setPositionMarker(global.customerMarker, null);
}
}

function formatTwoDecimals(pmonto) {
    var val = parseFloat(pmonto);
    if (isNaN(val)) { return "0.00"; }
    if (val <= 0) { return "0.00"; }
    val += "";
    // Next two lines remove anything beyond 2 decimal places 
    if (val.indexOf('.') == -1) { return val + ".00"; }
    else { val = val.substring(0, val.indexOf('.') + 3); }
    val = (val == Math.floor(val)) ? val + '.00' : ((val * 10 == Math.floor(val * 10)) ? val + '0' : val);
    return val;
}

function updateDirectionMarker(str) {
    //document.getElementById('Label_Localizacion_Info').innerText = str;
}

function selectNextSlideRoute() {

    var slider = getSliderRouter();

    if (global.currentSlideRouteNumber < globalList.trackDataByImei.length) {
        updateCurrentPositionRouteHistory(global.currentSlideRouteNumber);
    }

    var slideNumber = global.currentSlideRouteNumber + 1;
    if (slideNumber >= globalList.trackDataByImei.length) {
    }
    else {
        slider.set_value(slideNumber);
    }
}

function enableDisableSliderRoute(ptoEnable) {
    try {
        var slider = getSliderRouter();
        slider.set_enabled(ptoEnable);
        slider.repaint();
    }
    catch (e) {

    }
}

function updateSlideVisibleRoute(sender, args) {

    var slider = sender;

    updateSliderRoute(slider.get_value());

    if (global.currentSlideRouteNumber < globalList.trackDataByImei.length) {
        updateCurrentPositionRouteHistory(global.currentSlideRouteNumber);
    }
}

function updateSlideVisibleSpeed(sender, args) {

    var slideValue = sender.get_value();

    global.speedRouteHistory = 1100 - (slideValue * 100);

    if (global.slideInterval != null) {
        window.clearInterval(global.slideInterval);
        global.slideInterval = null;
        global.slideInterval = window.setInterval('selectNextSlideRoute()', global.speedRouteHistory);
    }
}

function updateSliderRoute(slideNumber) {
    global.currentSlideRouteNumber = slideNumber;
}

function meg_selectLastSlide(pstopSlideShow) {

    if (pstopSlideShow) {
        stopSlideMovement();
    }

    var slider = getSliderRouter();

    var slideNumber = global.currentSlideRouteNumber - 1;
    if (slideNumber == -1) {
        slideNumber = globalList.trackDataByImei.length - 1;
    }

    slider.set_value(slideNumber);
}

function playSlideMovement(){
    global.slideInterval = window.setInterval('selectNextSlideRoute()', global.speedRouteHistory);
}

function stopSlideMovement()
{
    if (!global.slideInterval) return;
    window.clearInterval(global.slideInterval);
    global.slideInterval = null;
}

function updateCurrentPositionRouteHistory(slideNumber) {
    objMapControl.setPositionMarker(objMapControl.car, globalList.trackDataByImei[slideNumber].position);
    getlbKmActual().innerText = formatTwoDecimals(globalList.trackDataByImei[slideNumber].currentKm) + " kms";
    getlbKmTime().innerText = globalList.trackDataByImei[slideNumber].hour;
    objMapControl.getDirectionFromPosition(globalList.trackDataByImei[slideNumber].position);
    centerMapChecked(globalList.trackDataByImei[slideNumber].position);
}

function centerMapChecked(location) {
    var ckbSiNoCenterVehicle = getCkbSiNoCenterVehicle();
    if (ckbSiNoCenterVehicle.checked) {
        objMapControl.centerMap(location);
    }
}

function addMarkerGeoFenceHistoryForUpdate(pgeoFence) {

    var position;

    for (li = 0; li < pgeoFence.numPosList.length; li++) {
        position = objMapControl.addPosition(parseFloat(pgeoFence.latitudeList[li].replace(",", ".")), parseFloat(pgeoFence.longitudeList[li].replace(",", "."))); //new google.maps.LatLng(parseFloat(pgeoFence.latitudeList[li].replace(",", ".")), parseFloat(pgeoFence.longitudeList[li].replace(",", ".")));
        objMapControl.addGeoFenceMarkersClicBD(position);
    }
}

function loadRouteHistory() {
    var imei = getImeiValueTreeVehicleSelected();
    var date = getDateSelected().get_textBox().value;
    if (imei == -1) {
        msgValidation('Debe seleccionar un vehículo para cargar la ruta.', titles.polygonoTitle);
    }
    else {

        if (date == "") {
            msgValidation('Debe seleccionar una fecha para cargar la ruta.', titles.polygonoTitle);
        }
        else {

            if (!isDate(date)){
                msgValidation('Debe seleccionar una fecha válida para cargar la ruta.', titles.polygonoTitle);
            }
            requestStart(getrpvRouteHistoryPanelUpdateControl());
            
            enableDisableSliderRoute(false);
            getBtnLoadRoute().disabled = true;
            getBtnPlayPause().set_enabled(false);
            PageMethods.wsLoadRouteHistory(imei, getFormatDate(date), loadRouteHistoryOk, loadRouteHistoryError);
        }
    }
}

function isDate(date){
    try{
        var newDate = new Date(date);
        return true;
    } catch (e) {
        return false;
    }
}

function getFormatDate(date)
{
    var day = date.substring(0, 2);
    var month = date.substring(3,5);
    var year = date.substring(6, 10);
    
    return year + '/' + month + '/' + day;
}

function loadRouteHistoryOk(stringCollection) {
    if (stringCollection == "") {
        msgInformation("No hay rutas definidas para la fecha seleccionada.", 'Historial de Rutas.');
        getBtnLoadRoute().value = "Cargar Ruta";
        getBtnLoadRoute().disabled = false;
        responseEnd(getrpvRouteHistoryPanelUpdateControl());
    }
    else {
        getBtnLoadRoute().value = "Cargando... 1%";
        objXmlControl.openCollectionStringTrackDataByImei(stringCollection);
        global.firstRoute = true;
        objMapControl.routes = [];
        drawDrivingRoute();
        }
    }

function loadRouteHistoryError(error) {
    msgError(error.get_message());
    responseEnd(getrpvRouteHistoryPanelUpdateControl());
}

function getImeiDataTrackLastLocationByUser() {
    PageMethods.wsGetImeiTrackDataLastLocationByUser(global.username, getImeiDataTrackLastLocationByUserOk, getImeiDataTrackLastLocationByUserError);
}

function getImeiDataTrackLastLocationByUserOk(xmlObject) {
    objXmlControl.openXMLTrackDataLastLocationImei(xmlObject);
}

function getImeiDataTrackLastLocationByUserError(error) {
    msgError(error.get_message(), titles.polygonoTitle);
}

function getGroupsTrackDataLastLocationByUser() {

    requestStart(getTreeLeftPanelUpdateControl());
    var tree = getMenuVehicleTree();

    try {
        tree.get_nodes().clear();
    }
    catch (e) { null; }

    PageMethods.wsGetGroupsTrackDataLastLocationByUser(global.username, getGroupsTrackDataLastLocationByUserOk, getGroupsTrackDataLastLocationByUserError);
}

function getGroupsTrackDataLastLocationByUserOk(xmlObject) {
    objXmlControl.openXMLTrackDataLastLocationGroupsImei(xmlObject);
    responseEnd(getTreeLeftPanelUpdateControl());
}

function getGroupsTrackDataLastLocationByUserError(error) {
    msgError(error.get_message(), titles.polygonoTitle);
    responseEnd(getTreeLeftPanelUpdateControl());
}

function existTrackDataLastLocationIntoTheList(imei) {
    for (ii = 0; ii < globalList.trackDataLastLocation.length; ii++) {
        if (imei == globalList.trackDataLastLocation[ii].imei) {
            return ii;
        }
    }
    return -1;
}

function existGeoFenceIDIntoTheList(geoFenceID) {
    var imei = getImeiValueTreeVehicleSelected();
    for (ii = 0; ii < globalList.geoFence.length; ii++) {
        if (imei == globalList.geoFence[ii].imei && globalList.geoFence[ii].geoFenceID == geoFenceID) {
            return ii;
        }
    }
    return -1;
}

function existCustomerIDIntoTheList(customerID, list) {
    for (ii = 0; ii < list.length; ii++) {
        if (list[ii].customerID == customerID) {
            return ii;
        }
    }
    return -1;
}

function existImeiIntoTheList(imei, list) {
    for (ii = 0; ii < list.length; ii++) {
        if (list[ii].imei == imei) {
            return ii;
        }
    }
    return -1;
}

function existCustomerGroupIDIntoTheList(customerGroupID) {
    for (ii = 0; ii < globalList.customersGroups.length; ii++) {
        if (globalList.customersGroups[ii].customerGroupID == customerGroupID) {
            return ii;
        }
    }
    return -1;
}

function getCustomersGroupsByUser() {
    requestStart(getrpvCustomersUpdateControl());
    PageMethods.wsGetCustomersGroupsByUsername(global.username, getCustomersGroupsByUserOk, getCustomersGroupsByUserError);
}

function getCustomersGroupsByUserOk(object) {
    objXmlControl.openXMLCustomersGroupsByUsername(object);
    loadCustomersGroupsDataSource();
    responseEnd(getrpvCustomersUpdateControl());
}

function getCustomersGroupsByUserError(error) {
    responseEnd(getrpvCustomersUpdateControl());
    msgError(error.get_message(), titles.customerTitle);
}

function getCustomersByUsernameAndCustomerGroupID() {
        requestStart(getrpvCustomersUpdateControl());
        PageMethods.wsGetCustomersByUsernameAndCustomerGroupID(global.username, global.customerGroupID, getCustomersByUsernameAndCustomerGroupIDOk, getCustomersByUsernameAndCustomerGroupIDError);
}

function getCustomersByUsernameAndCustomerGroupIDOk(object) {
    objXmlControl.openXMLCustomersByUsernameAndCustomerGroupID(object);
    loadCustomersDataSource();
    responseEnd(getrpvCustomersUpdateControl());
}

function getCustomersByUsernameAndCustomerGroupIDError(error) {
    responseEnd(getrpvCustomersUpdateControl());
    msgError(error.get_message(), titles.customerTitle);
}

function insertCustomer() {
    var customerName = getRtbCustomerName().value;
    var lat;
    var lng;
    try {
        objMapControl.getPositionMarker(global.customerMarker);
        lat = stringToFloatForPosition(objMapControl.getPositionXtoString(objMapControl.getPositionMarker(global.customerMarker)));
        lng = stringToFloatForPosition(objMapControl.getPositionYtoString(objMapControl.getPositionMarker(global.customerMarker)));
    }
    catch (e) {
        msgValidation("No se ha ingresado el marcador del Cliente.", titles.customerTitle);
        responseEnd(getrpvCustomersUpdateControl());
        return;
    }

    if (global.customerGroupID != -1) {
        if (customerName != "") {
            requestStart(getrpvCustomersUpdateControl());
            PageMethods.wsInsertCustomer(customerName, global.customerGroupID, lat, lng, insertCustomerOk, insertCustomerError);
        }
        else {
            msgValidation("No se ha ingresado el nombre del cliente.", titles.customerTitle);
        }
    }
    else{
        msgValidation("No se ha seleccionado el grupo de clientes.", titles.customerTitle);
    }
}

function insertCustomerOk(id)
{
    var myCustomer = new Customer();
    myCustomer.setCustomer(id, getRtbCustomerName().value, objMapControl.getPositionXtoString(objMapControl.getPositionMarker(global.customerMarker)), objMapControl.getPositionYtoString(objMapControl.getPositionMarker(global.customerMarker)));
    myCustomer.checked = true;
    globalList.customers.push(myCustomer);
    loadCustomersDataSource();
    showAllCustomersChecked();
    selectLastItemByCustomer();
    objMapControl.setPositionMarker(global.customerMarker, null);
    responseEnd(getrpvCustomersUpdateControl());
    msgInformation("Se registró correctamente el Cliente.", titles.customerTitle);
}

function insertCustomerError(error)
{
    responseEnd(getrpvCustomersUpdateControl());
    msgError(error.get_message(), titles.customerTitle);
}

function insertGeoFence() {

    var polygonoName = getRtbPolygonName().value;
    var imei = getImeiValueTreeVehicleSelected();

    if (imei != -1) {
        if (polygonoName != "") {
            var latitudePolygonoList = []; //X
            var longitudePolygonoList = []; //Y

            if (objMapControl.polygonoMarkers.length > 2) {
                for (i = 0; i < objMapControl.polygonoMarkers.length; i++) {
                    latitudePolygonoList.push(objMapControl.getPositionXtoString(objMapControl.getPositionMarker(objMapControl.polygonoMarkers[i])));
                    longitudePolygonoList.push(objMapControl.getPositionYtoString(objMapControl.getPositionMarker(objMapControl.polygonoMarkers[i])));   
                }
                requestStart(getrpvGeoFencePanelUpdateControl());
                PageMethods.wsInsertGeoFence(imei, polygonoName, latitudePolygonoList, longitudePolygonoList, insertGeoFenceOk, insertGeoFenceError);

            } else {
                msgInformation("Debe existir mínimo tres marcadores para crear un polígono.", titles.polygonoTitle);
            }
        }
        else {
            msgValidation("Debe registrar un nombre para guardar el polígono.", titles.polygonoTitle);
        }
    }
    else {
        msgValidation("Debe seleccionar un vehículo antes de guardar el polígono.", titles.polygonoTitle);
    }
}

function configDecimalSeparator(str)
{
    return str;//.replace(".",",");
}

function stringToFloatForPosition(str) {
    return parseFloat(str.replace(",", "."));
}

function insertGeoFenceOk(geoFenceDetails) {
    getRtbPolygonName().value = "";
    objXmlControl.openXMLGeoFenceDetailsByGeoFenceID(geoFenceDetails);   
    responseEnd(getrpvGeoFencePanelUpdateControl());
    var imei = getImeiValueTreeVehicleSelected();
    selectLastItemByImei(imei);
    msgInformation("Se registró correctamente el polígono.", titles.polygonoTitle);
    
}

function insertGeoFenceError(error) {
    responseEnd(getrpvGeoFencePanelUpdateControl());
    msgError(error.get_message(), titles.polygonoTitle);
}

//Begin Messages

function msg(mgs, titulo) {
    new Messi(mgs, { title: titulo, buttons: [{ id: 0, label: 'Aceptar', val: 'X' }], modal: true });
}

function msgSuccess(mgs, titulo) {
    new Messi(mgs, { title: titulo, titleClass: 'success', buttons: [{ id: 0, label: 'Aceptar', val: 'X' }], modal: true });
}

function msgInformation(mgs, titulo) {
    new Messi(mgs, { title: titulo, titleClass: 'info', buttons: [{ id: 0, label: 'Aceptar', val: 'X' }], modal: true });
}

function msgValidation(mgs, titulo) {
    new Messi(mgs, { title: titulo, titleClass: 'warning', buttons: [{ id: 0, label: 'Aceptar', val: 'X' }], modal: true });
}

function msgError(mgs, titulo) {
    new Messi(mgs, { title: titulo, titleClass: 'anim error', buttons: [{ id: 0, label: 'Aceptar', val: 'X' }], modal: true });
}

//End Messages

function getAllGeoFenceIntoList() {
    PageMethods.wsGetAllGeoFenceDetails(global.username, getAllGeoFenceIntoListOk, getAllGeoFenceIntoListError);
}

function getAllGeoFenceIntoListOk(xmlObject) {
    objXmlControl.openXMLGeoFenceDetails(xmlObject);
}

function clearGeoFenceList() {
    for (i = 0; i < globalList.geoFence.length; i++) {
        globalList.geoFence.pop(); //Clear the GeoFence list.
    }
}

function clearCustomerList() {

    var length = globalList.customers.length;

    for (iii = 0; iii < length; iii++) {
        globalList.customers.pop();
    }

}

function loadGeoFenceGridByImei(pimei) {

    var tableView = getGeoFenceGrid();
    clearGeoFenceDataSource();

    for (iii = 0; iii < globalList.geoFence.length; iii++) {
        if (globalList.geoFence[iii].imei == pimei) {
            globalDataSource.geoFence.push({ "GeoFenceId": globalList.geoFence[iii].geoFenceID, "Description": globalList.geoFence[iii].description });
        }
    }

    tableView.set_dataSource(globalDataSource.geoFence);
    tableView.dataBind();
}

function clearList(list){
    var length = list.length;
    for (i = 0; i < length; i++)
    {
        list.pop();
    }
}

//Begin Load DataSources

function clearCustomersGroupsDataSource() {
    var length = globalDataSource.customersGroups.length;
    for (i = 0; i < length; i++) {
        globalDataSource.customersGroups.pop(); //Clear the globalDataSource.customersGroups list.
    }
}

function clearGeoFenceDataSource() {
    var length = globalDataSource.geoFence.length;
    for (i = 0; i < length; i++) {
        globalDataSource.geoFence.pop(); //Clear the globalDataSource.geoFence list.
    }
}

function clearCustomersDataSource() {
    var length = globalDataSource.customers.length;
    for (i = 0; i < length; i++) {
        globalDataSource.customers.pop(); //Clear the globalDataSource.customers list.
    }

    getCustomerGrid().clearSelectedItems();

    var tableView = getCustomerGrid();

    tableView.set_dataSource(globalDataSource.customers);
    tableView.dataBind();

}

function clearDataSource(listDataSource) {
    var length = listDataSource.length;
    for (i = 0; i < length; i++) {
        listDataSource.pop();
    }
}

function loadUsersRouteByAdminDataSource() {

    var tableView = getUsersRoutesGrid();
    clearDataSource(globalDataSource.usersRoute);

    for (iii = 0; iii < globalList.users.length; iii++) {
        globalDataSource.usersRoute.push({ "Username": globalList.users[iii].username, "Name": globalList.users[iii].name, "FirstName": globalList.users[iii].firstName, "LastName": globalList.users[iii].lastName });
    }

    tableView.set_dataSource(globalDataSource.usersRoute);
    tableView.dataBind();
}

function loadCustomersGroupsDataSource() {

    var tableView = getCustomersGroupsGrid();
    
    for (iii = 0; iii < globalList.customersGroups.length; iii++) {
        globalDataSource.customersGroups.push({ "CustomerGroupID": globalList.customersGroups[iii].customerGroupID, "CustomerGroupName": globalList.customersGroups[iii].customerGroupName });
    }

    //clearCustomersGroupsDataSource();
    tableView.set_dataSource(globalDataSource.customersGroups);
    tableView.dataBind();
}

function loadCustomersGroupsRoutesSelectedDataSource(){
    var tableView = getCustomersGroupsRoutesSelectedGrid();
    clearDataSource(globalDataSource.allCustomersSelected);
    

    for (iii = 0; iii < globalList.allCustomers.length; iii++) {
        if (globalList.allCustomers[iii].checked) {
            objMapControl.setVisibleMarker(globalList.allCustomers[iii].marker, true);
            globalDataSource.allCustomersSelected.push({ "CustomerID": globalList.allCustomers[iii].customerID, "NumPos": globalList.allCustomers[iii].numPos, "CustomerName": globalList.allCustomers[iii].customerName, "CustomerGroupName": globalList.allCustomers[iii].customerGroupName });
        }
    }
    tableView.clearSelectedItems();
    tableView.set_dataSource(globalDataSource.allCustomersSelected);
    tableView.dataBind();
}
function loadCustomersGroupsRoutesDataSource() {

    var tableView = getCustomersGroupsRoutesGrid();
    clearDataSource(globalDataSource.allCustomers);
    //tableView.clearSelectedItems();

    for (iii = 0; iii < globalList.allCustomers.length; iii++) {
        if (!globalList.allCustomers[iii].checked) {
            globalDataSource.allCustomers.push({ "CustomerID": globalList.allCustomers[iii].customerID, "CustomerName": globalList.allCustomers[iii].customerName, "CustomerGroupName": globalList.allCustomers[iii].customerGroupName });
            objMapControl.setVisibleMarker(globalList.allCustomers[iii].marker, false);
            objMapControl.hideClientsRoutes();
        }
    }

    tableView.set_dataSource(globalDataSource.allCustomers);
    tableView.dataBind();
}

function addRowCustomersGroupsRouteDataSource(index) {
    var tableView = getCustomersGroupsRoutesSelectedGrid();
    
    globalDataSource.allCustomersSelected.push({ "NumPos": globalList.allCustomers[index].numPos, "CustomerID": globalList.allCustomers[index].customerID, "CustomerName": globalList.allCustomers[index].customerName, "CustomerGroupName": globalList.allCustomers[index].customerGroupName, "KmsText": globalList.allCustomers[index].kmsText, "DurationText": globalList.allCustomers[index].durationText });

    tableView.set_dataSource(globalDataSource.allCustomersSelected);
    tableView.dataBind();
}

function loadCustomersDataSource() {

    var tableView = getCustomerGrid();
    clearCustomersDataSource();

    for (iii = 0; iii < globalList.customers.length; iii++) {
        globalDataSource.customers.push({ "CustomerID": globalList.customers[iii].customerID, "CustomerName": globalList.customers[iii].customerName });
    }

    tableView.set_dataSource(globalDataSource.customers);
    tableView.dataBind();
}

function loadImeiDataSource() {

    var tableView = getGpsRoutesGrid();
    clearDataSource(globalDataSource.imei);
    tableView.clearSelectedItems();

    for (iii = 0; iii < globalList.imei.length; iii++) {
        globalDataSource.imei.push({ "Imei": globalList.imei[iii].imei, "Name": globalList.imei[iii].name });
    }

    tableView.set_dataSource(globalDataSource.imei);
    tableView.dataBind();
}

//End Load DataSources

function getAllGeoFenceIntoListError(error) {
    msgError(error.get_message());
}

function showHideHistoryRoute() {
    var ckbSiNoShowRoute = getCkbSiNoShowRoute();
    if (ckbSiNoShowRoute.checked) {
        showHistoryRoute();
    }
    else {
        hideHistoryRoute();
    }
}

function showOrhideStopsMarkers() {
    if (getCkbSiNoShowStops().checked) {
        showStopsMarkers();
    }
    else {
        hideStopsMarkers();
    }
}

function hideStopsMarkers(){
    for(i=0;i<globalList.stopsMarkers.length;i++){
        objMapControl.setVisibleMarker(globalList.stopsMarkers[i].stopMarker, false);
    }
}

function showStopsMarkers() {
    for (i = 0; i < globalList.stopsMarkers.length; i++) {
        objMapControl.setVisibleMarker(globalList.stopsMarkers[i].stopMarker, true);
    }
}

function showOrHideAllGeoFenceFromSelect(pshow) {

    var geoFenceIDSelected = global.geoFenceIDSelected;
    var imei = getImeiValueTreeVehicleSelected();

    for (lk = 0; lk < globalList.geoFence.length; lk++) {
        if (pshow) {
            if (geoFenceIDSelected != globalList.geoFence[lk].geoFenceID && imei == globalList.geoFence[lk].imei) {
                globalList.geoFence[lk].showGeoFence();
            }
            else {
                if (imei != globalList.geoFence[lk].imei) {
                    globalList.geoFence[lk].hideGeoFence();
                }
            }
        }
        else {
            globalList.geoFence[lk].hideGeoFence();
        }
    }
}



function changeDirectionPosition(initialPosition, finalPosition)
{
    var NS = ''; //(-)
    var OE = ''; //(|)
    if (stringToFloatForPosition(objMapControl.getPositionXtoString(finalPosition)) < stringToFloatForPosition(objMapControl.getPositionXtoString(initialPosition))) { NS = 'N'; }
    if (stringToFloatForPosition(objMapControl.getPositionXtoString(finalPosition)) > stringToFloatForPosition(objMapControl.getPositionXtoString(initialPosition))) { NS = 'S'; }
    if (stringToFloatForPosition(objMapControl.getPositionYtoString(finalPosition)) > stringToFloatForPosition(objMapControl.getPositionYtoString(initialPosition))) { OE = 'E'; }
    if (stringToFloatForPosition(objMapControl.getPositionYtoString(finalPosition)) < stringToFloatForPosition(objMapControl.getPositionYtoString(initialPosition))) { OE = 'O'; }
    
    var direction = NS + OE;
    if (global.lastCardinalPoint != "")
    {
        if (global.lastCardinalPoint != direction) {
            if ((global.lastCardinalPoint == "NO" && direction == "SE") || (global.lastCardinalPoint == "SE" && direction == "NO") || (global.lastCardinalPoint == "NE" && direction == "SO") || (global.lastCardinalPoint == "SO" && direction == "NE"))// || (global.lastCardinalPoint == "NE" && direction == "NO") || (global.lastCardinalPoint == "NO" && direction == "NE") || (global.lastCardinalPoint == "NO" && direction == "SO") || (global.lastCardinalPoint == "SO" && direction == "NO") || (global.lastCardinalPoint == "NE" && direction == "SE") || (global.lastCardinalPoint == "SE" && direction == "NE"))
            {
                global.lastCardinalPoint = direction;
                return true;
            }
        }
    }
    global.lastCardinalPoint = direction;
    return false;
}



function drawDrivingRoute() {
    global.currentGpsPoint = 0;
    global.firstRoute = true;
    objMapControl.clearStopsMarkers();
    showHistoryRoute();
    global.doesnWorkDrawRoute = false;
    global.lastOne = false;
    global.mtsRoute = global.mtsRouteStar;
    global.refreshIntervalId = setInterval(drawDrivingRouteTimer, 100);
    responseEnd(getrpvRouteHistoryPanelUpdateControl());
}

function drawDrivingRouteTimer() {

    if (globalList.trackDataByImei.length > 1) {
        var lstart = 0;
        
        var existsMarker = false;
        var stopTimes = 0;
        var initialStop = 0;

        for (global.currentGpsPoint = global.currentGpsPoint; global.currentGpsPoint < globalList.trackDataByImei.length - 2; global.currentGpsPoint++) {
            getBtnLoadRoute().value = "Cargando..." + formatTwoDecimals((global.currentGpsPoint / globalList.trackDataByImei.length) * 100) + "%";

            if (lstart == 0) {
                if (globalList.trackDataByImei[global.currentGpsPoint + 1].currentKm - globalList.trackDataByImei[global.currentGpsPoint].currentKm >= global.mtsRoute) {
                    if (global.doesnWorkDrawRoute) {
                        global.doesnWorkDrawRoute = false;
                        lstart = 0;
                        global.destination = globalList.trackDataByImei[global.currentGpsPoint].position;
                        objMapControl.getDrivingRoute();
                        return;
                    }
                    else {
                        lstart = 1;
                        global.origin = globalList.trackDataByImei[global.currentGpsPoint].position;
                        if (globalList.stopsMarkers.length > 0 && globalList.stopsMarkers[globalList.stopsMarkers.length - 1].finalTimeStop == null) {
                            globalList.stopsMarkers[globalList.stopsMarkers.length - 1].finalTimeStop = globalList.trackDataByImei[global.currentGpsPoint].hour;
                        }
                    }
                }
                else {
                    if (globalList.trackDataByImei[global.currentGpsPoint + 1].currentKm - globalList.trackDataByImei[global.currentGpsPoint].currentKm < global.mtsStop) {
                    if (!existsMarker) {
                        if (initialStop == 0) {
                                initialStop = globalList.trackDataByImei[global.currentGpsPoint].hour;
                        }
                            if (stopTimes > global.timesStop) {

                            var myStopMarker = new StopMarker();

                                myStopMarker.setStopMarker(objMapControl.addStopMarker(images.locationStop, globalList.trackDataByImei[global.currentGpsPoint].position, ""), objMapControl.addInfoWindow(), initialStop);

                            if (!getCkbSiNoShowStops().checked) {
                                myStopMarker.stopMarker.setVisible(false);
                            }

                                globalList.stopsMarkers.push(myStopMarker);

                            existsMarker = true;
                        }
                        else {
                            stopTimes++;
                        }
                    }
                    else {
                            if (globalList.stopsMarkers.length > 0) {
                                globalList.stopsMarkers[globalList.stopsMarkers.length - 1].finalTimeStop = globalList.trackDataByImei[global.currentGpsPoint].hour;
                            }
                        }
                    }
                }
            } else {
                if ((globalList.trackDataByImei[global.currentGpsPoint + 1].currentKm - globalList.trackDataByImei[global.currentGpsPoint].currentKm < global.mtsRoute) || (changeDirectionPosition(globalList.trackDataByImei[global.currentGpsPoint].position, globalList.trackDataByImei[global.currentGpsPoint + 1].position))) {
                        lstart = 0;
                    global.destination = globalList.trackDataByImei[global.currentGpsPoint + 1].position;

                    objMapControl.getDrivingRoute();
                        return;
                }
            }
        }
        if (lstart = 1) {
            global.destination = globalList.trackDataByImei[global.currentGpsPoint + 1].position;
            global.lastOne = true;
            setTimeout(objMapControl.getDrivingRoute, 1000);
        }
        drawDrivingRouteFinish();
    }


}

function drawDrivingRouteFinish() {
    clearInterval(global.refreshIntervalId);
    getBtnLoadRoute().value = "Cargar Ruta";
    getBtnLoadRoute().disabled = false;
    getBtnPlayPause().set_enabled(true);

    slider = getSliderRouter();
    slider.set_maximumValue(globalList.trackDataByImei.length - 1);

    global.currentSlideRouteNumber = 0;

    if (globalList.trackDataByImei.length > 0) {
        var imei = getImeiValueTreeVehicleSelected();
        var index = existTrackDataLastLocationIntoTheList(imei);
        if (index != -1) {
            objMapControl.setIconMarker(objMapControl.car, globalList.trackDataLastLocation[index].image);
        }

        updateCurrentPositionRouteHistory(global.currentSlideRouteNumber);

        slider.set_value(0);

        getlbKmFinal().innerHTML = formatTwoDecimals(globalList.trackDataByImei[globalList.trackDataByImei.length - 1].currentKm) + " kms";
        enableDisableSliderRoute(true);
    }
    else {
        enableDisableSliderRoute(false);
    }
}

function geoFence_ShowAllGeoFenceIDChecked()
{
    var imei = getImeiValueTreeVehicleSelected();

    for (lk = 0; lk < globalList.geoFence.length; lk++) {
        
        if (globalList.geoFence[lk].checked && imei == globalList.geoFence[lk].imei) {
            globalList.geoFence[lk].showGeoFence();
        }
        else {
            globalList.geoFence[lk].hideGeoFence();
        }
    }

}

function showAllCustomersChecked() {
    for (lk = 0; lk < globalList.customers.length; lk++) {
        globalList.customers[lk].marker.setVisible(globalList.customers[lk].checked);
    }
}

function clearCustomerMarkers() {
    for (k = 0; k < globalList.customers.length; k++) {
        globalList.customers[k].checked = false;
        getCustomerGrid().clearSelectedItems();
    }
}

function refreshCustomer() {
    clearNumPosClients();
    clearKmsAndDurationClients(true);
    global.isClear = true;
    loadCustomersGroupsRoutesDataSource();
    getCustomersGroupsRoutesGrid().clearSelectedItems();
    loadCustomersGroupsRoutesSelectedDataSource();
    getCustomersGroupsRoutesSelectedGrid().clearSelectedItems();
    global.isClear = false;
}

function generateRoutes()
{
    global.cantErrors = 0;
    requestStart(getrpvRoutesPanelUpdateControl());
    refreshCustomer();
    objMapControl.clientsRoutes = [];
    global.firstClientRoute = true;
    
    clearDataSource(globalDataSource.allCustomersSelected);
    global.numPos = 0;
    clearNumPosClients();

    if (getCantClientSelected() > 1) {
        calculateSmartRoute(null);
    }
    else {
        msgValidation("Debe seleccionar almenos dos clientes para generar la ruta", "Generación de Rutas");
    }

}

function calculateSmartRoute(address) {

    global.currentIndexRoute = -1;
    global.currentIndexNearClient = -1;
    clearKmsAndDurationClients();

    if (nextPositionIndexRoute()) {
        objMapControl.calculateSmartRouteStart(address);
    }
    else {
        responseEnd(getrpvRoutesPanelUpdateControl());
        //drawGenerateRoutes();
    }
}

function getCantClientSelected() {
    var cantClientSelected = 0;
    for (cont = 0; cont < globalList.allCustomers.length; cont++) {
        if (globalList.allCustomers[cont].checked) {
            cantClientSelected++;
        }
    }
    return cantClientSelected;
}

function clearNumPosClients() {
    for (cont = 0; cont < globalList.allCustomers.length; cont++) {
        globalList.allCustomers[cont].numPos = null;
    }
}

function clearKmsAndDurationClients(clearAll) {
    for (cont = 0; cont < globalList.allCustomers.length; cont++) {
        if (globalList.allCustomers[cont].numPos == null || clearAll) {
            globalList.allCustomers[cont].kms = null;
            globalList.allCustomers[cont].kmsText = null;
            globalList.allCustomers[cont].duration = null;
            globalList.allCustomers[cont].durationText = null;
        }
    }
}

/*function drawGenerateRoutes()
{
    global.numPos = 1;
    global.currentIndexRoute = -1;
    objMapControl.clientsRoutes = [];
    global.firstClientRoute = true;
    if (nextPositionIndexRoutetoDraw()) {
        objMapControl.getValidOriginLocation(objMapControl.originImeiMarker.position.lat() + "," + objMapControl.originImeiMarker.position.lng());
    }
}*/

function nextPositionIndexRoutetoDraw()
{
    for (global.currentIndexRoute = 0; global.currentIndexRoute < globalList.allCustomers.length; global.currentIndexRoute++) {
        if (globalList.allCustomers[global.currentIndexRoute].numPos == global.numPos) {
            global.numPos++;
            return true;
        }
    }
    return false;
}

function nextPositionIndexRoute() {
    for(global.currentIndexRoute = global.currentIndexRoute + 1; global.currentIndexRoute < globalList.allCustomers.length; global.currentIndexRoute++){
        if(globalList.allCustomers[global.currentIndexRoute].checked && globalList.allCustomers[global.currentIndexRoute].numPos == null){
            return true;
        }    
    }
    return false;
}

/*function generateRoutesBackup() {
    var cont = 0;
    for (i = 0; i < globalList.allCustomers.length; i++) {

        if (globalList.allCustomers[i].checked) {
            if (cont == 0) {
                objMapControl.getValidOriginLocation(globalList.allCustomers[i].address + "," + globalList.allCustomers[i].position.lng());
                cont++;
            }
            else {
                objMapControl.getValidDestinationLocation(globalList.allCustomers[i].position.lat() + "," + globalList.allCustomers[i].position.lng());
            }
        }
    }
}*/

function saveRoutes()
{

}